package com.hqizcc.ltcs.hqbsltcs.service;

import com.hqizcc.ltcs.hqbsltcs.common.Global;
import com.hqizcc.ltcs.hqbsltcs.mapper.GetCityMapper;
import com.hqizcc.ltcs.hqbsltcs.mapper.GetProvinceMapper;
import com.hqizcc.ltcs.hqbsltcs.model.City;
import com.hqizcc.ltcs.hqbsltcs.model.Province;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class GetCityServiceImpl implements GetCityService {

    @Autowired
    private GetCityMapper getCityMapper;

    @Autowired
    private GetProvinceMapper getProvinceMapper;

    @Override
    public boolean getCity() {

        List<Province> pList = getProvinceMapper.queryProvince();

        City city = new City();

        for (Province province : pList){

            String htmlUrl = province.getProvinceHtml();

            Element body = null;
            try {

                body = Jsoup.connect(htmlUrl).ignoreContentType(true).timeout(600000).get().body();

                Elements elements = body.select(".citytr");

                for (Element element : elements){

                    String cityNameAndId = element.select("td a").text();


                    city.setCityHtml(element.select("td a").attr("href").toString());

                    city.setCityId(cityNameAndId.substring(0, 12));

                    city.setCityName(new String(cityNameAndId.substring(13).getBytes(), "UTF-8"));

                    city.setCityHtml(Global.URL + city.getCityHtml());

//                    System.out.println(city.getCityId() + " " + city.getCityName() + " " + city.getCityHtml());

                    getCityMapper.saveProvinceIdAndCityId(province.getProvinceId(), city.getCityId());

                    getCityMapper.saveCity(city.getCityId(), city.getCityName(), city.getCityHtml());

                }

            } catch (IOException e) {

                e.printStackTrace();

                return false;
            }

        }

        return true;

    }
}
